package utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.text.BadLocationException;

import javax.swing.text.Element;
import javax.swing.text.ElementIterator;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.parser.ParserDelegator;

/**
 * author @fikipollo
 *
 * Esta clase contine todo el código necesario para manejar el código HTML de
 * las páginas web
 *
 *
 */
public class HTMLParser {

    public static String downloadURL(String direccionUrl) throws MiException {
        try {
            URL dir = new URL(direccionUrl);
            URLConnection yc = dir.openConnection();

            // Aqu� agregamos unas cabeceras a la petici�n para "saltar" la seguridad de algunos sitios
            // as� piensan que somos un navegador.
            yc.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; es-ES; rv:1.9.0.10) Gecko/2009042316 Firefox/3.0.10");
            yc.addRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            yc.addRequestProperty("Accept-Language", "es-es,es;q=0.8,en-us;q=0.5,en;q=0.3");
            yc.setConnectTimeout(3000);
            
            // Creamos el objeto con el que vamos a leer
            BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream(),"ISO8859_1"));
            String inputLine;
            String retorno = "";
            while ((inputLine = in.readLine()) != null) {
                retorno += inputLine + "\n";
            }
            in.close();
            return retorno;
        } catch (Exception ex) {
            throw new MiException("Error en downloadURL para dirección " + direccionUrl);
        }
        // Si llegamos aqu� hubo una excepci�n y devolvemos null
//        return null;
    }

    public void printChildrens(Element elem, int level) {
        if (elem != null) {
            for (int tab = 0; tab < level; tab++) {
                System.out.print("\t");
            }

            System.out.print(elem.getName());
            if (elem.getName().equalsIgnoreCase("img")) {
                String s = (String) elem.getAttributes().getAttribute(HTML.Attribute.TITLE);
                if (s != null) {
                    System.out.print(s);
                }
            } else if (elem.getName().equalsIgnoreCase("content")) {
                Enumeration<?> acac = elem.getAttributes().getAttributeNames();
                while (acac.hasMoreElements()) {
                    String name = acac.nextElement().toString();
                    System.out.print(name + ", ");
                    // String s = elem.getAttributes().getAttribute(name).toString();
                    // if (s != null)
                    // System.out.print(s);
                }

            }
            System.out.println("\n");

            for (int i = 0; i < elem.getElementCount(); i++) {
                printChildrens(elem.getElement(i), level + 1);
            }
        }
    }

    public void parser(String data) throws Exception {
        HTMLEditorKit kit = new HTMLEditorKit();
        HTMLDocument doc = (HTMLDocument) kit.createDefaultDocument();
        doc.putProperty("IgnoreCharsetDirective", Boolean.TRUE);
        StringReader br = new StringReader(data);

        kit.read(br, doc, 0);
        

        // Get an iterator for all HTML tags.
        ElementIterator it = new ElementIterator(doc);
        Element elem;

        while ((elem = it.next()) != null) {
            new HTMLParser().printChildrens(elem, 0);
            // System.out.println(elem.getName());
            // for(int i= 0; i < elem.getElementCount(); i++){
            //
            // }
            //
            // if (elem.getName().equals("img")) {
            // String s = (String) elem.getAttributes().getAttribute(HTML.Attribute.TITLE);
            // if (s != null)
            // System.out.println(s);
            // }
        }
    }

    public static ArrayList<Tupla> extractLinks(String data) throws MiException {
        StringReader s = null;
        s = new StringReader(data);
        ParserDelegator hp = new ParserDelegator();
        final ArrayList<Tupla> links = new ArrayList<Tupla>();

        try {
            hp.parse(s, new HTMLEditorKit.ParserCallback() {

                public void handleStartTag(HTML.Tag t, MutableAttributeSet a, int pos) {
                    if (t == HTML.Tag.A) {
                        Tupla tupla = new Tupla(null, null);
                        Enumeration attrNames = a.getAttributeNames();
                        while (attrNames.hasMoreElements()) {
                            Object key = attrNames.nextElement();
                            if ("href".equals(key.toString())) {
                                tupla.setElem2(a.getAttribute(key).toString());
//								System.out.println(a.getAttribute(key));
                            } else if ("title".equals(key.toString())) {
                                tupla.setElem1(a.getAttribute(key).toString());
//								System.out.println(a.getAttribute(key));
                            }
                        }
                        links.add(tupla);
                    }
                }
            }, true);
        } catch (IOException e) {
            throw new MiException("Error en extractLinks");
        } finally {
            if (s != null) {
                s.close();
            }
        }

        return links;
    }

    public static String[] extractDownloadLinks(String data) {
        String[] links = data.split("\n");
        return links;
    }

    public static String extractOnlineLink(String data) {
        data = data.split("value=" + '"')[1];
        data = data.replace("" + '"' + " />\n", "");
        return data;
    }

    public static String[] extractDescripcionAndKeywords(String data) throws MiException {
        try {
            String[] info = new String[4];
            String[] aux;
            HTMLEditorKit kit = new HTMLEditorKit();
            HTMLDocument doc = (HTMLDocument) kit.createDefaultDocument();
            doc.putProperty("IgnoreCharsetDirective", Boolean.TRUE);
            StringReader br = new StringReader(data);
            kit.read(br, doc, 0);
            // Get an iterator for all HTML tags.
            ElementIterator it = new ElementIterator(doc);
            Element elem;
            while ((elem = it.next()) != null) {
                if (elem != null) {
                    if (elem.getName().equalsIgnoreCase("meta")) {
                        String s = (String) elem.getAttributes().getAttribute(HTML.Attribute.NAME);
                        if (s != null) {
                            if (s.equals("description")) {
                                s = (String) elem.getAttributes().getAttribute(HTML.Attribute.CONTENT);
                                aux = s.split(" - ", 3);
                                info[0] = aux[1];
                                info[1] = aux[0];
                                info[2] = aux[2];
                            }
                            if (s.equals("keywords")) {
                                s = (String) elem.getAttributes().getAttribute(HTML.Attribute.CONTENT);
                                info[3] = "Keywords: " + s;
                            }
                        }
                    }
                }
                if ((info[0] != null) && (info[1] != null) && (info[2] != null) && (info[3] != null)) {
                    return info;
                }
            }
            return null;
        } catch (IOException ex) {
            Logger.getLogger(HTMLParser.class.getName()).log(Level.SEVERE, null, ex);
            throw new MiException("Error la extraer info de la pelicula");

        } catch (BadLocationException ex) {
            Logger.getLogger(HTMLParser.class.getName()).log(Level.SEVERE, null, ex);
            throw new MiException("Error la extraer info de la pelicula");
        }
    }
}
